package com.kingsalert.kingsalert.view.process_widget;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;

import com.kingsalert.kingsalert.R;
import com.kingsalert.kingsalert.base.BaseApplication;
import com.kingsalert.kingsalert.base.BaseProcessWidgetManager;
import com.kingsalert.kingsalert.bean.process.ProcessInfo_Data;
import com.kingsalert.kingsalert.bean.userinfo.OthersInfo;
import com.kingsalert.kingsalert.config.Constant;
import com.kingsalert.kingsalert.config.PermissionConfig;
import com.kingsalert.kingsalert.dialog.PhotoSelectorDialog;
import com.kingsalert.kingsalert.util.http.HttpUtil;
import com.kingsalert.kingsalert.util.image.ImageConvert;

import java.io.File;
import java.util.TreeMap;

import pub.devrel.easypermissions.EasyPermissions;

public class OcrViewManager extends BaseProcessWidgetManager {

    private FragmentActivity activity;

    private View idcardView,passportView,drvinglicenseView;
    private ImageView idcardIv,passportIv,drvinglicenseIv;
    private TextView imgTypeTitleTv;
    private ImageButton img1Ib,img2Ib;
    private TextView img1Tv,img2Tv;
    private View img2View;

    private String image1Url, image2Url;
    private Bitmap image1Bitmap, image2Bitmap;

    private boolean isImageReverse = false;

    private static final String CT_IdCard="National ID card",CT_Passport="Passport",CT_DrvingLicense="Drving license";
    private static final String WD_IdCard="IDCARD",WD_Passport="PASSPORT",WD_DrvingLicense="DRIVING";

    private String selectType = CT_IdCard;

    private Runnable startCameraRunnable;

    public String imgPath = "";
    public Uri photoUri;

    public static final int Flag_StartCamera = 56;

    private ActivityResultLauncher<PickVisualMediaRequest> pickMedia;

    private final Runnable processRespRunnable,imgUploadRespRunnable;

    public OcrViewManager(View view, ProcessInfo_Data data,String page,Runnable processRespRunnable,Runnable imgUploadRespRunnable){
        super(view,data,page);
        activity = (FragmentActivity) mView.getContext();

        this.processRespRunnable = processRespRunnable;
        this.imgUploadRespRunnable = imgUploadRespRunnable;
    }

    @Override
    protected void init(){

        idcardView = mView.findViewById(R.id.vpo_view_idcard);
        passportView = mView.findViewById(R.id.vpo_view_passport);
        drvinglicenseView = mView.findViewById(R.id.vpo_view_drvinglicense);
        idcardIv = mView.findViewById(R.id.vpo_iv_idcard);
        passportIv = mView.findViewById(R.id.vpo_iv_passport);
        drvinglicenseIv = mView.findViewById(R.id.vpo_iv_drvinglicense);
        imgTypeTitleTv = mView.findViewById(R.id.vpo_tv_img_type_title);
        img1Ib = mView.findViewById(R.id.vpo_ib_img1);
        img2Ib = mView.findViewById(R.id.vpo_ib_img2);
        img1Tv = mView.findViewById(R.id.vpo_tv_img1);
        img2Tv = mView.findViewById(R.id.vpo_tv_img2);
        img2View = mView.findViewById(R.id.vpo_view_img2);
        
        img1Ib.setOnClickListener(v -> {

            HttpUtil.getInstance().saveBuriedPoint(page ,"IMAGE_1_CLICK","");

            new PhotoSelectorDialog(
                    mView.getContext(),
                    () -> {//打开相机
                        isImageReverse = false;
                        startCamera();
                    },
                    () -> {//相册选择
                        isImageReverse = false;
                        openAlbum();
                    }
            ).show();

        });

        img2Ib.setOnClickListener(v -> {
            HttpUtil.getInstance().saveBuriedPoint(page,"IMAGE_2_CLICK","");

            new PhotoSelectorDialog(
                    mView.getContext(),
                    () -> {//打开相机
                        isImageReverse = true;
                        startCamera();
                    },
                    () -> {//相册选择
                        isImageReverse = true;
                        openAlbum();
                    }
            ).show();

        });

        idcardView.setOnClickListener(v -> initTypeIdCard());
        passportView.setOnClickListener(v -> initTypePassport());
        drvinglicenseView.setOnClickListener(v -> initTypeDrvingLicense());

        initTypeIdCard();
        
    }

    public void nextClick(String path){
        if (TextUtils.isEmpty(image1Url)||(TextUtils.isEmpty(image2Url)&&!selectType.equalsIgnoreCase(CT_Passport))){
            Toast.makeText(mView.getContext(),mView.getContext().getString(R.string.upload_ocr_tip),Toast.LENGTH_SHORT).show();
            return;
        }

        HttpUtil.getInstance().submitProcessInfo(
                activity,
                path,
                new TreeMap<String,String>(){{
                    put("cardImgUrl", image1Url);
                    put("cardBackImgUrl", selectType.equalsIgnoreCase(CT_Passport) ? "":image2Url);
                    put("cardType",getTypeWd());
                }},
                () -> HttpUtil.getInstance().userProcess(activity,() -> {if (processRespRunnable!=null) processRespRunnable.run();}
        ));
    }

    @Override
    public boolean checkInput() {
        return false;
    }

    @Override
    public String getInput() {
        return "";
    }


    private void startCamera(){

        HttpUtil.getInstance().saveBuriedPoint(page ,"START_CAMERA_CLICK","");

        //拍照流程
        startCameraRunnable = () -> {
            Intent intent = new Intent();
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

            String imageFilePath = this.getImageFilePath();
            File imageFile = new File(imageFilePath);
            imgPath = imageFilePath;
            String providerAuthority = BaseApplication.getInstant().getPackageName() + ".file_provider";
            photoUri = FileProvider.getUriForFile(BaseApplication.getInstant(), providerAuthority, imageFile);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            if (activity!=null) activity.startActivityForResult(intent, Flag_StartCamera);
        };
        //申请权限
        if (!PermissionConfig.checkPermissions(mView.getContext(), Manifest.permission.CAMERA)) {
            if (activity!=null)
                EasyPermissions.requestPermissions(activity, "App requires camera permission.", PermissionConfig.PermissionCode_Camera, Manifest.permission.CAMERA);
        } else startCameraRunnable.run();
    }

    private void openAlbum(){

        HttpUtil.getInstance().saveBuriedPoint(page ,"OPEN_ALBUM_CLICK","");

        if (pickMedia!=null)
            pickMedia.launch(
                    new PickVisualMediaRequest.Builder()
                            .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                            .build()
            );
    }

    public void setPickMedia(ActivityResultLauncher<PickVisualMediaRequest> pickMedia) {
        this.pickMedia = pickMedia;
    }

    public void onPhotoGet() {
        if (photoUri == null) {
            if (isImageReverse) image2Url = null;
            else image1Url = null;
            Toast.makeText(mView.getContext(),mView.getContext().getString(R.string.photo_upload_again_tip),Toast.LENGTH_SHORT).show();
            return;
        }

        if (!TextUtils.isEmpty(imgPath)) {
            ImageConvert.startConvertImage(
                    new File(imgPath),
                    (localPath, thumpImg) -> {
                        if (isImageReverse) image2Bitmap = thumpImg;
                        else image1Bitmap = thumpImg;
                        new Thread(() -> HttpUtil.getInstance().uploadImg(activity,localPath,() -> {
                            if (imgUploadRespRunnable!=null) imgUploadRespRunnable.run();
                        })).start();
                    }
            );
        } else {
            if (isImageReverse) image2Url = null;
            else image1Url = null;
            Toast.makeText(mView.getContext(),mView.getContext().getString(R.string.photo_upload_again_tip),Toast.LENGTH_SHORT).show();
        }
    }

    public void onPhotoUploadResponse(){

        String imagePath = OthersInfo.getInstance().getImgPath();

        if (TextUtils.isEmpty(imagePath)||(!isImageReverse&& image1Bitmap ==null)||(isImageReverse&& image2Bitmap ==null)){
            Toast.makeText(mView.getContext(),mView.getContext().getString(R.string.photo_upload_again_tip),Toast.LENGTH_SHORT).show();
            return;
        }

        if (isImageReverse){
            this.image2Url = imagePath;
            img2Ib.setImageBitmap(image2Bitmap);
        }else {
            this.image1Url = imagePath;
            img1Ib.setImageBitmap(image1Bitmap);
        }
    }

    @SuppressLint("SetTextI18n")
    private void initTypeIdCard(){

        HttpUtil.getInstance().saveBuriedPoint(page ,"TYPE_ID_CARD_CLICK","");

        idcardView.setBackgroundResource(R.drawable.bg_green_ll_rc10dp_border_greenmain_1dp);
        passportView.setBackgroundResource(R.drawable.bg_gray_rc10dp);
        drvinglicenseView.setBackgroundResource(R.drawable.bg_gray_rc10dp);
        idcardIv.setBackgroundResource(R.drawable.icon_ocr_type_check_true);
        passportIv.setBackgroundResource(R.drawable.icon_ocr_type_check_false);
        drvinglicenseIv.setBackgroundResource(R.drawable.icon_ocr_type_check_false);

        imgTypeTitleTv.setText(mView.getContext().getString(R.string.ocr_type_idcard));

        clearImg();

        selectType = CT_IdCard;
        img1Tv.setText(mView.getContext().getString(R.string.ocr_idcard_front));
        img2Tv.setText(mView.getContext().getString(R.string.ocr_idcard_back));
        img2View.setVisibility(View.VISIBLE);
    }

    @SuppressLint("SetTextI18n")
    private void initTypePassport(){

        HttpUtil.getInstance().saveBuriedPoint(page ,"TYPE_PASSPORT_CLICK","");

        idcardView.setBackgroundResource(R.drawable.bg_gray_rc10dp);
        passportView.setBackgroundResource(R.drawable.bg_green_ll_rc10dp_border_greenmain_1dp);
        drvinglicenseView.setBackgroundResource(R.drawable.bg_gray_rc10dp);
        idcardIv.setBackgroundResource(R.drawable.icon_ocr_type_check_false);
        passportIv.setBackgroundResource(R.drawable.icon_ocr_type_check_true);
        drvinglicenseIv.setBackgroundResource(R.drawable.icon_ocr_type_check_false);

        imgTypeTitleTv.setText(mView.getContext().getString(R.string.ocr_type_passport));

        clearImg();

        selectType = CT_Passport;
        img1Tv.setText(mView.getContext().getString(R.string.ocr_passport));
        img2View.setVisibility(View.GONE);

    }

    @SuppressLint("SetTextI18n")
    private void initTypeDrvingLicense(){

        HttpUtil.getInstance().saveBuriedPoint(page ,"TYPE_DRIVING_LICENSE_CLICK","");

        idcardView.setBackgroundResource(R.drawable.bg_gray_rc10dp);
        passportView.setBackgroundResource(R.drawable.bg_gray_rc10dp);
        drvinglicenseView.setBackgroundResource(R.drawable.bg_green_ll_rc10dp_border_greenmain_1dp);
        idcardIv.setBackgroundResource(R.drawable.icon_ocr_type_check_false);
        passportIv.setBackgroundResource(R.drawable.icon_ocr_type_check_false);
        drvinglicenseIv.setBackgroundResource(R.drawable.icon_ocr_type_check_true);

        imgTypeTitleTv.setText(mView.getContext().getString(R.string.ocr_type_drvinglicense));

        clearImg();

        selectType = CT_DrvingLicense;
        img1Tv.setText(mView.getContext().getString(R.string.ocr_drvinglicense_front));
        img2Tv.setText(mView.getContext().getString(R.string.ocr_drvinglicense_back));
        img2View.setVisibility(View.VISIBLE);

    }

    private void clearImg(){
        image1Url = "";
        image2Url = "";
        image1Bitmap = null;
        image2Bitmap = null;

        img1Ib.setImageResource(R.drawable.img_ocr_front);
        img2Ib.setImageResource(R.drawable.img_ocr_back);
    }

    private String getTypeWd(){
        switch (selectType){
            case CT_IdCard:
                return WD_IdCard;
            case CT_Passport:
                return WD_Passport;
            case CT_DrvingLicense:
                return WD_DrvingLicense;
        }
        return "";
    }

    public void onCameraPermissionAgree(){
        if (startCameraRunnable!=null) startCameraRunnable.run();
    }

    /**
     * 获取图片路径
     */
    private String getImageFilePath() {
        String pictureId = System.currentTimeMillis() + "";
        String imgDir = getSandboxFolderPath();
        return (imgDir + File.separator + pictureId + ".jpg");
    }

    /**
     * 获取沙盒路径
     */
    private String getSandboxFolderPath() {
        String inAppFolder = BaseApplication.getInstant().getFilesDir().getAbsolutePath();
        inAppFolder += File.separator;
        inAppFolder += Constant.PRODUCT;
        inAppFolder += "_PICS";

        File folderFile = new File(inAppFolder);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        return inAppFolder;
    }

}
